package com.syher.seconds.kill.web.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.syher.seconds.kill.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("order")
public class OrderController {

    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    IOrderService orderService;
    RateLimiter rateLimiter = RateLimiter.create(10);

    @RequestMapping("/createWrongOrder/{sid}")
    public String createWrongOrder(@PathVariable int sid) {
        logger.info("sid=[{}]", sid);
        //限流
        if (!rateLimiter.tryAcquire(3000, TimeUnit.MILLISECONDS)) {
            return "服务器繁忙";
        }

        int id = 0;
        try {
            //id = orderService.createWrongOrder(sid);

            //id = orderService.createOptimisticOrder(sid);

            //id = orderService.createOptimisticOrderUseRedis(sid);

            orderService.createOptimisticOrderUseKafka(sid);
        } catch (Exception e) {
            logger.error("Exception", e);
        }
        return String.valueOf(id);
    }
}
